package msa.ch03.data;

import java.util.Vector;

import msa.ch03.MessageArrivalListener;

public class MessageDatabase {

	/** Singleton instance */
	private static MessageDatabase instance = new MessageDatabase();

	private final Vector messageList = new Vector();
	private MessageArrivalListener mal;
	
	/**
	 * Private constructor to avoid instantiation
	 */
	private MessageDatabase() {

	}

	/**
	 * @return Singleton instance
	 */
	public static MessageDatabase getInstance() {
		return instance;
	}
	
	public void setMessageArrivalListener(MessageArrivalListener mal) {
		this.mal = mal;
	}
	
	public synchronized void addMessage(StoredMessage message) {
		messageList.addElement(message);
		mal.messageArrived(message);
	}
	
	public synchronized StoredMessage[] list() {
		StoredMessage[] list = new StoredMessage[messageList.size()];
		messageList.copyInto(list);
		return list;
	}
	
	public synchronized StoredMessage get(int i) {
		StoredMessage item = (StoredMessage) messageList.elementAt(i);
		return item;
	}
}
